JSON

JSON.stringify() 语法增强

JSON.stringify('\u{D800}')
// '\ud880'

Array

const arr = [1, [2, 3], [4, 5, [6, 7]]]

// 扁平化:以规定的深度递归数组
// 深度默认为 1
const arr = [1, 2, 3]

// flatMap: flat + map
arr.flatMap(item => [item * 2]) // [1, 2, 3]
// 相当于
// arr.map(item => [item * 2]).flat()

String

const str = '   foo   '

const s1 = str.trimLeft() // 别名: trimStart
// 相当于
// str.replace(/^\s+/g, '')
console.log(s1) // 'foo   '

const s2 = str.trimRight() // 别名: trimEnd
// 相当于
// str.replace(/\s+$/g, '')
console.log(s2) // '   foo'

const s3 = str.trim()
// 相当于
// str.replace(/^\s+|\s+$/g, '')
console.log(s3) // 'foo'

console.log(str) // '   foo   '
// 以上操作都不改变原字符串
const str = `"foo" and "bar" and "baz"`
// 如何提取 foo、bar、baz?

// before
function select(regExp, str) {
    const matches = []
    while (true) {
        const match = regExp.exec(str)
        if (match === null) break
        matches.push(match[1])
    }
    return matches
}
select(/"([^"]*)"/g, str) // ["foo", "bar", "baz"]

// 或
str.match(/"([^"]*)"/g) // [""foo"", ""bar"", ""baz""]

// 或
function select(regExp, str) {
    const matches = []
    str.replace(regExp, (all, first) => {
        matches.push(first)
    })
    return matches
}
select(/"([^"]*)"/g, str) // ["foo", "bar", "baz"]

// --------------------------
// after
function select(regExp, str) {
    const matches = []
    for (const match of str.matchAll(regExp)) {
        matches.push(match[1])
    }
    return matches
}
select(/"([^"]*)"/g, str) // ["foo", "bar", "baz"]

// str.matchAll(/"([^"]*)"/g) // RegExpStringIterator {}

Object

const arr = [['foo', 1], ['bar', 2]]
const obj = Object.fromEntries(arr)
console.log(obj) // { foo: 1, bar: 2 }

// 反向操作
const obj = { foo: 1, bar: 2 }
const arr = Object.entries(obj)
console.log(arr) // [['foo', 1], ['bar', 2]]

// 应用场景:Array 的 API 多于 Object,转换后可以调用 Array 的 API

try...catch

// before
try {} catch (e) {}

// after
try {} catch {}
// (e) 可以省略,ES10 之前不可以

BigInt

const a = 11n
const b = 11
typeof a // bigint
typeof b // number

11n + 22n // 33n